

class XMLDocument 
  attr_accessor :name
  attr_accessor :attributes
  attr_accessor :content
  attr_accessor :childElements
  attr_accessor :xmlString

  def initialize(xmlString)
    @xmlString = xmlString
    @childElements = Array.new(0)

    if isNextNewTag
      getNewTag
      if contentExist
        getContent
      end

      while !isNextEndTag
        # recursive call
        @childElements.push(XMLDocument.new(@xmlString))
      end

      getEndTag
    end

  end

  def getNameAndAttributes(xmlString, attributesExist)

    if attributesExist
      spacePos = xmlString.index " "
      attributeString = xmlString[(spacePos + 1)..(xmlString.length - 1)]

      @name = xmlString[0..(spacePos - 1)]
      @attributes = attributeString.split " "
    else
      @name = xmlString
    end

  end

  # return true if tag is attribute only
  def getNewTag
    attributeOnlyDetector = false
    attributeDetector = false
    start = @xmlString.index "<"
    stop = @xmlString.index ">"

    

    attributeStop = @xmlString.index "/>"

    if attributeStop
      if (stop - 1) == attributeStop
        attributeOnlyDetector = true
        stop = attributeStop
      end
    end

    tempString = @xmlString[(start + 1)..(stop - 1)]

    if(tempString.index " ")
      attributeDetector = true
    end

    getNameAndAttributes(@xmlString[(start + 1)...(stop)], attributeDetector)


    @xmlString.slice!(start..stop)
    return attributeOnlyDetector
  end

  def getContent
    buf = @xmlString.index "<"
    if nil != buf
      @content = @xmlString.split " "
    end
  end

  def getEndTag
    start = @xmlString.index "</"
    stop = @xmlString.index ">"

    @xmlString.slice!(start..stop)
  end

  def getAttributes(attributeString)
    @attributes = attributeString.split " "
  end

  def contentExist
    openEndTag = @xmlString.index "</"
    openTag = @xmlString.index "<"

    # if the first character is not the beginning
    # of new tag data, then we must have some content
    if openEndTag != 0 or openTag != 0
      return true
    else
      return false
    end

  end
      
  def isNextNewTag
    openEndTag = @xmlString.index "</"
    openTag = @xmlString.index "<"

    return openTag < openEndTag
  end

  def isNextEndTag
    openEndTag = @xmlString.index "</"
    openTag = @xmlString.index "<"

    return openEndTag == openTag
  end

  def printXMLData
    puts "NAME:" + @name
    puts "Printing #{@childElements.length} for #{@name}: "

    @childElements.each { |element|
      element.printXMLData
    }
  end

end
